layui.config({
  version: '1593348928630' //为了更新 js 缓存，可忽略
});

layui.use(['laydate', 'laypage', 'layer', 'table', 'carousel', 'upload', 'element', 'slider', 'form'], function () {
  var laydate = layui.laydate //日期
    , $ = layui.$
    , layer = layui.layer //弹层
    , table = layui.table //表格
    , element = layui.element
    , form = layui.form
    , talkUrls = jsRoutes.controllers.admin.RobotMsgController.talk()
    , messageUrls = jsRoutes.controllers.admin.RobotMsgController.message()
    , indexUrls = jsRoutes.controllers.admin.RobotMsgController.index()
  var talkdemotable , msgdemotable
  var layid = location.hash.replace("#", '');
  console.log(layid);
  element.tabChange('accTabBrief', layid);
  accList(layid, { "op": "list" })
  //向世界问个好
  element.on('tab(accTabBrief)', function (data) {
    layer.msg('切到到了' + data.index + '：' + this.innerHTML);
    location.hash = this.getAttribute('lay-id');
    layid = location.hash.replace("#", '');
    console.log(data)
//    accList(layid, { "op": "list" })
  });
  laydate.render({
    elem: '#sendtime' //指定元素
    , type: 'datetime'
    , range: '~' //true
    , format: 'yyyy-MM-ddTHH:mm:ss'
  });

  function accList(layid, data) {
    if (layid == 'talks') {
      //执行一个 table 实例
      talkdemotable = table.render({
        elem: '#demoRobotTalk'
        , contentType: 'application/json'
        , method: talkUrls.method
        , height: 550
        , url: talkUrls.url //数据接口
        , title: '用户表'
        , page: true //开启分页
        , toolbar: 'default' //开启工具栏，此处显示默认图标，可以自定义模板，详见文档
        , headers: {"Csrf-Token": $('[name="csrfToken"]').val()}
        , where: data
        , cols: [[ //表头
          { type: 'checkbox', fixed: 'left' }
          , { field: 'id', title: 'ID', width: 80, sort: true, fixed: 'left' }
          , { field: 'name', title: '群名', width: 130 }
          , { field: 'access', title: ' access', width: 130 }
          , { field: 'status', title: '启用', width: 130 }
          , { field: 'note', title: '备注', width: 180 }
          , { fixed: 'right', title: '操作', width: 200, align: 'center', toolbar: '#barDemo' }
        ]]
      });
    }
    if (layid == 'messages') {
      //执行一个 table 实例
      msgdemotable = table.render({
        elem: '#demoRobotMsg'
        , contentType: 'application/json'
        , method: messageUrls.method
        , height: 550
        , url: messageUrls.url //数据接口
        , title: '部门表'
        , page: true //开启分页
        , toolbar: 'default' //开启工具栏，此处显示默认图标，可以自定义模板，详见文档
        , headers: {"Csrf-Token": $('[name="csrfToken"]').val()}
        , where: data
        , cols: [[ //表头
          { type: 'checkbox', fixed: 'left' }
          , { field: 'id', title: 'ID', width: 120, sort: true, fixed: 'left' }
          , { field: 'talk', title: '会话', width: 130 }
          , { field: 'title', title: '标题', width: 130 }
          , { field: 'msg', title: '消息', width: 120, sort: true }
          , { field: 'runtime', title: '发送时间', width: 100, sort: true }
          , { field: 'lostTime', title: '过期时间', width: 120, sort: true }
          , { field: 'sendStatus', title: '状态', width: 120, sort: true }
          , { fixed: 'right', title: '操作', width: 200, align: 'center', toolbar: '#barDemo' }
        ]]
      });
    }
  }

  // 监听头工具栏事件
  table.on('toolbar(testrobottalk)', function (obj) {
    var checkStatus = table.checkStatus(obj.config.id)
      , data = checkStatus.data; //获取选中的数据
    var str_home = '<form class="layui-form" lay-filter="barDemoEditForm">';
    var str_name = '<div class="layui-form-item "><label class="layui-form-label ">群名</label><div class="layui-input-block ">';    
    var str_access = '</div></div><div class="layui-form-item"><label class="layui-form-label">access</label><div class="layui-input-block ">';
    var str_secret = '</div></div><div class="layui-form-item"><label class="layui-form-label">secret</label><div class="layui-input-block ">';
    var str_status = '</div></div><div class="layui-form-item"><label class="layui-form-label">启用</label><div class="layui-input-block ">';
    var str_note = '</div></div><div class="layui-form-item"><label class="layui-form-label">说明</label><div class="layui-input-block ">';
    var str_id = '</div></div><div class="layui-form-item"><label class="layui-form-label">ID</label><div class="layui-input-block ">';
    var str_end = '</div></div></form>';
    switch (obj.event) {
      case 'add':
        //    layer.msg('添加');
        var create_name = '<input type="text"  name="name" value="" class="layui-input" lay-verify="required" style="width:85%;" >';
        var create_access = '<input type="text"  name="access" value="" class="layui-input" lay-verify="required" style="width:85%;" >';
        var create_secret = '<input type="text"  name="secret" value="" class="layui-input" lay-verify="required" style="width:85%;" >';
        var create_status = '<input type="text"  name="status" value="" class="layui-input" lay-verify="required" style="width:85%;" >';
        var create_note = '<input type="text" name="note" value="" class="layui-input" style="width:85%;">';
        var str_content = str_home + str_name + create_name + str_access + create_access + str_secret + create_secret + str_status + create_status + str_note + create_note + str_end //这里content是一个普通的String
        // console.log(str_content)
        layer.open({
          type: 1
          , area: '500px'
          , content: str_content
          , btn: ['提交', '关闭']
          , yes: function (index, layero) {
            //按钮【按钮一】的回调
            console.log(index)
            var data = form.val("barDemoEditForm")
            var load_index = layer.load(1, { time: 30 * 1000 });
            $.post({
              url: talkUrls.url,
              contentType: 'application/json; charset=UTF-8',
              headers: {"Csrf-Token": $('[name="csrfToken"]').val()},
              data: JSON.stringify({ "name": data.name, "access": data.access, "secret": data.secret, "status": data.status, "note": data.note }),
              //                 dataType: 'text',
              success: function (data) {
                console.log(data);
                layer.close(load_index);
                layer.msg("数据: \n" + data + "\n状态: " + status);
                talkdemotable.reload();
              }
            });
            layer.close(index);
          }
          , btn2: function (index, layero) {
            //按钮【按钮二】的回调
            //return false 开启该代码可禁止点击该按钮关闭
          }
          , cancel: function () {
            //右上角关闭回调
            //return false 开启该代码可禁止点击该按钮关闭
          }

        });
        break;
      case 'update':
        if (data.length === 0) {
          layer.msg('请选择一行');
        } else if (data.length > 1) {
          layer.msg('只能同时编辑一个');
        } else {
          console.log(checkStatus.data)
          //layer.alert('编辑 [id]：'+ checkStatus.data[0].name);
          var update_name =   '<input type="text" name="name"   value="'+ checkStatus.data[0].name +'" class="layui-input" lay-verify="required" style="width:85%;" >';
          var update_access = '<input type="text" readonly name="access" value="'+ checkStatus.data[0].access +'" class="layui-input" lay-verify="required" style="width:85%;" >';
          var update_secret = '<input type="text" name="secret" value="'+ checkStatus.data[0].secret +'" class="layui-input" lay-verify="required" style="width:85%;" >';
          var update_status = '<input type="text" name="status" value="'+ checkStatus.data[0].status +'" class="layui-input" lay-verify="required" style="width:85%;" >';
          var update_note =   '<input type="text" name="note"   value="'+ checkStatus.data[0].note +'" class="layui-input" style="width:85%;">';
          var update_id =  '<input type="text" name="id" hidden value="'+ checkStatus.data[0].id +'" class="layui-input" lay-verify="required" style="width:85%;">';
          var str_content = str_home + str_name + update_name + str_access + update_access + str_secret + update_secret + str_status + update_status + str_note + update_note + str_id + update_id + str_end //这里content是一个普通的String
          layer.open({
            type: 1
            , area: '500px'
            ,content: str_content  //这里content是一个普通的String
            , btn: ['提交', '关闭']

            , yes: function (index, layero) {
              //按钮【按钮一】的回调
              console.log(index);
              var data = layero.context.forms[0];

              var load_index = layer.load(1, { time: 30 * 1000 });

              $.post({
                url: talkUrls.url,
                contentType: 'application/json; charset=UTF-8',
                headers: {"Csrf-Token": $('[name="csrfToken"]').val()},
                data: JSON.stringify({ "op": "update", "name": data[0].value, "password": data[1].value, "note": data[2].value }),
                //                    dataType: 'text',
                success: function (data) {
                  console.log(data);
                  layer.close(load_index);
                  layer.msg("数据: \n" + data + "\n状态: " + status);
                  talkdemotable.reload();
                }
              });
              layer.close(index);

            }
            , btn2: function (index, layero) {
              //按钮【按钮二】的回调

              //return false 开启该代码可禁止点击该按钮关闭
            }
            , cancel: function () {
              //右上角关闭回调

              //return false 开启该代码可禁止点击该按钮关闭
            }

          });
        }
        break;
      case 'delete':
        if (data.length === 0) {
          layer.msg('请选择一行');
        } else {
          layer.msg('删除');
          console.log(data)

        }
        break;
    };
  });

  table.on('toolbar(testrobotmsg)', function (obj) {
    var checkStatus = table.checkStatus(obj.config.id)
      , data = checkStatus.data; //获取选中的数据
    var str1 = '<form class="layui-form" ><div class="layui-form-item"><label class="layui-form-label">SSID</label><div class="layui-input-block ">';
    var str3 = '</div></div><div class="layui-form-item"><label class="layui-form-label">密码</label><div class="layui-input-block ">';
    var str5 = '</div></div><div class="layui-form-item"><label class="layui-form-label">说明</label><div class="layui-input-block ">';
    var str7 = '</div></div></form>';
    switch (obj.event) {
      case 'add':
        //    layer.msg('添加');
        var create_name = '<input type="text"  name="name" value="" class="layui-input" lay-verify="required">';
        var create_password = '<input type="password" name="password" class="layui-input" lay-verify="required">';
        var create_note = '<input type="text" name="note" value="" class="layui-input" >';
        layer.open({
          type: 1
          , area: '500px'
          , content: str1 + create_name + str3 + create_password + str5 + create_note + str7 //这里content是一个普通的String
          , btn: ['提交', '关闭']
          , yes: function (index, layero) {
            //按钮【按钮一】的回调
            console.log(index)
            var data = layero.context.forms[0]
            var load_index = layer.load(1, { time: 30 * 1000 });
            $.post({
              url: messageUrls.url,
              contentType: 'application/json; charset=UTF-8',
              headers: {"Csrf-Token": $('[name="csrfToken"]').val()},
              data: JSON.stringify({ "op": "create", "name": data[0].value, "password": data[1].value, "note": data[2].value }),
              //                 dataType: 'text',
              success: function (data) {
                console.log(data);
                layer.close(load_index);
                layer.msg("数据: \n" + data + "\n状态: " + status);
                msgdemotable.reload();
              }
            });
            layer.close(index);
          }
          , btn2: function (index, layero) {
            //按钮【按钮二】的回调
            //return false 开启该代码可禁止点击该按钮关闭
          }
          , cancel: function () {
            //右上角关闭回调
            //return false 开启该代码可禁止点击该按钮关闭
          }

        });
        break;
      case 'update':
        if (data.length === 0) {
          layer.msg('请选择一行');
        } else if (data.length > 1) {
          layer.msg('只能同时编辑一个');
        } else {
          console.log(checkStatus.data)
          //layer.alert('编辑 [id]：'+ checkStatus.data[0].name);

        }
        break;
      case 'delete':
        if (data.length === 0) {
          layer.msg('请选择一行');
        } else {
          layer.msg('删除');
          console.log(data)
          layer.open({
            type: 1,
            content: "确定要删除SSID：<code>" + checkStatus.data[0].name + "<code>？"  //这里content是一个普通的String
            , btn: ['提交', '关闭']

            , yes: function (index, layero) {
              //按钮【按钮一】的回调
              console.log(index);
              var data = layero.context.forms[0];

              var load_index = layer.load(1, { time: 30 * 1000 });
              var idArr = []
              for (i=0;i<data.length;i++){idArr.push(data[i].id);}

              $.post({
                url: messageUrls.url,
                contentType: 'application/json; charset=UTF-8',
                headers: {"Csrf-Token": $('[name="csrfToken"]').val()},
                data: JSON.stringify({ option:"delete",key:"id",id:idArr}),
                //                    dataType: 'text',
                success: function (data) {
                  console.log(data);
                  layer.close(load_index);
                  layer.msg("数据: \n" + data + "\n状态: " + status);
                  msgdemotable.reload();
                }
              });
              layer.close(index);

            }
            , btn2: function (index, layero) {
              //按钮【按钮二】的回调

              //return false 开启该代码可禁止点击该按钮关闭
            }
            , cancel: function () {
              //右上角关闭回调

              //return false 开启该代码可禁止点击该按钮关闭
            }
          });


        }
        break;
    };
  });



  //监听行工具事件
  table.on('tool(test)', function (obj) { //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
    var data = obj.data //获得当前行数据
      , layEvent = obj.event; //获得 lay-event 对应的值
    if (layEvent === 'onoff') {
      layer.msg('启停操作');
      var userArr = []
      userArr.push(data);
      $.post({
        url: postUrls.url,
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify({ option: "onoff", id: userArr }),
        dataType: 'text',
        success: function (data) {
          console.log(data);
          alert("数据: \n" + data + "\n状态: " + status);
          demotable.reload();
        }
      });
    } else if (layEvent === 'del') {
      layer.confirm('真的删除行么', function (index) {
        layer.close(index);
        //向服务端发送删除指令
        console.log(data.id);
        var userArr = []
        userArr.push(data.id);
        $.post({
          url: postUrls.url,
          contentType: 'application/json',
          data: JSON.stringify({ option: "delete", id: userArr }),
          dataType: 'text',
          success: function (data) {
            console.log(data);
            alert("数据: \n" + data + "\n状态: " + status);
            obj.del(); //删除对应行（tr）的DOM结构

          }
        });


      });
    } else if (layEvent === 'edit') {
      layer.msg('编辑操作');
      console.log(data.id);
    }
  });

  form.on('submit(formrobottalk)', function (data) {
    layid = location.hash.replace("#", '');
    console.log(data)
    accList("talks", data.field);
    return false;
  });

  form.on('submit(formrobotmsg)', function (data) {
    layid = location.hash.replace("#", '');
    accList("messages", data.field);
    return false;
  });


});

